package com.geostar.constructionland.analyse.service.automatic;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.geostar.constructionland.analyse.entity.HttpResult;
import com.geostar.constructionland.analyse.entity.model.AnalyseModel;
import com.geostar.constructionland.analyse.entity.resulthandler.HandlerResult;
import com.geostar.constructionland.analyse.mapper.LspwFileLogMapper;
import com.geostar.constructionland.analyse.service.AnalyseService;
import com.geostar.constructionland.analyse.service.HttpAPIService;
import com.geostar.constructionland.analyse.service.automatic.entity.CoordinateFile;
import com.geostar.constructionland.analyse.service.automatic.entity.LspwFileLog;
import com.geostar.constructionland.analyse.service.automatic.util.FileUtil;
import com.geostar.constructionland.common.entity.response.ServerResponse;
import com.geostar.constructionland.common.global.AnalyseType;
import com.geostar.constructionland.common.util.CpdetectorEncoding;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.charset.Charset;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author yelll
 * @since 2020-7-8 10:17
 **/
@Service
@Slf4j
public class AutomaticService {
    @Autowired
    HttpAPIService httpAPIService;
    @Autowired
    ObjectMapper objectMapper;
    @Autowired
    CoordinateFileProxy coordinateFileProxy;
    @Value("${automatic.coordinate-check}")
    String coordinateCheckUrl;
    @Value("${automatic.yhid}")
    String yhid;
    @Value("${automatic.jbxx.lcdm}")
    String lcdm;
    @Value("${automatic.jbxx.ywdl}")
    String ywdl;
    @Value("${automatic.jbxx.ywxl}")
    String ywxl;
    @Value("${automatic.jbxx.ywlx}")
    String ywlx;
    @Value("${automatic.jbxx.pclx}")
    String pclx;
    @Value("${automatic.jbxx.url}")
    String jbxxCreateUrl;
    @Value("${automatic.coordinate-trans}")
    String coordinateTransUrl;
    @Value("${automatic.txtUpload}")
    String txtUploadUrl;
    @Value("${automatic.batchTxtUpload}")
    String batchTxtUpload;
    @Value("${automatic.updateJbxx}")
    String updateJbxxUrl;
    @Value("${automatic.overlap}")
    String overlapUrl;

    @Value("${automatic.selfIntersect}")
    String selfIntersectUrl;

    @Value("${automatic.insertDkxx}")
    String insertDkxxUrl;

    @Value("${automatic.batchTransCoord}")
    String batchTransCoordUrl;

    @Autowired
    LspwFileLogMapper lspwFileLogMapper;
    @Value("${automatic.md5_valid_flag}")
    String md5ValidFlag;
    @Value("${automatic.queryExport}")
    String queryExport;
    @Value("${automatic.downExport}")
    String downExport;
    @Value("${automatic.tmpFilePath}")
    String tmpFilePath;
    @Value("${automatic.deleteFxData}")
    String deleteFxDataUrl;
    /**
     * 自动化处理
     * @return
     */
    public ServerResponse automatic(String fileContent, String fileName, String fileMd5, String userId){
        log.info("文本内容:{},文件名称:{},文件MD5:{}",fileContent,fileName,fileMd5);
        LspwFileLog lspwFileLog = new LspwFileLog();
        lspwFileLog.setUploadTime(new Date());
        lspwFileLog.setFileName(fileName);
        lspwFileLog.setMd5(fileMd5);
        lspwFileLog.setCreateUserId(userId);
        if(md5ValidFlag.equals("1")){
            /**进行MD5验证*/
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("md5",fileMd5);
            queryWrapper.eq("status","1");
            queryWrapper.eq("create_user_id",userId);
            List<LspwFileLog> lspwFileLogs = lspwFileLogMapper.selectList(queryWrapper);
            if(lspwFileLogs.size() > 0){
                lspwFileLog.setErrorMsg("存在已经处理成功的相同文件,文件名:"+lspwFileLogs.get(0).getFileName());
                lspwFileLogMapper.insert(lspwFileLog);
                return  ServerResponse.createByErrorMessage("存在已经处理成功的相同文件,文件名:"+lspwFileLogs.get(0).getFileName());
            }
        }
        String ywid = "";
        /**读取文件*/
        try {
            ywid = createJsydJbxx(userId);
            log.info("创建案卷,ywid：{}",ywid);
            if(StringUtils.isBlank(ywid)){
                lspwFileLog.setErrorMsg("创建案卷不成功!");
                lspwFileLogMapper.insert(lspwFileLog);
                return  ServerResponse.createByErrorMessage("创建案卷不成功!");
            }
            lspwFileLog.setYwid(ywid);
            String fileIdStr = uploadTxtFile(fileContent,ywid,fileName);
            Map fjMap = objectMapper.readValue(fileIdStr,Map.class);
            if(!fjMap.containsKey("fjid") && StringUtils.isBlank(fjMap.get("fjid").toString())){
                lspwFileLog.setErrorMsg("上传失败");
                lspwFileLogMapper.insert(lspwFileLog);
                return  ServerResponse.createByErrorMessage("上传文件失败!");
            }
            lspwFileLog.setFjid(fjMap.get("fjid").toString());
            log.info("上传文件成功，文件信息：{}",fjMap.get("fjid").toString());
            boolean isCoordinateCheckOk = coordinateCheck(fileContent);
            if(isCoordinateCheckOk){
                CoordinateFile coordinateFile = coordinateFileProxy.proxyFileContent(fileContent);
                String overlapInfo = overlapCheck(coordinateFile);
                Map<String,Object> overlapInfoMap = objectMapper.readValue(overlapInfo,Map.class);
                List<Object> overlapList = (List<Object>)overlapInfoMap.get("ProcessValue");
                log.info("重叠分析成功,内容：{}",overlapInfo);
                if(overlapList.size() > 0){
                    lspwFileLog.setErrorMsg("检查->有重叠");
                    lspwFileLogMapper.insert(lspwFileLog);
                    return ServerResponse.createByErrorMessage("检查->有重叠");
                }
                String selfIntersectInfo = selfIntersectCheck(coordinateFile);
                log.info("自相交,内容：{}",selfIntersectInfo);
                Map<String,Object> selfIntersectInfoMap = objectMapper.readValue(selfIntersectInfo,Map.class);
                List<Object> selfIntersectList = (List<Object>)selfIntersectInfoMap.get("ProcessValue");
                if(selfIntersectList.size() > 0){
                    lspwFileLog.setErrorMsg("检查->存在自相交");
                    lspwFileLogMapper.insert(lspwFileLog);
                    return ServerResponse.createByErrorMessage("检查->存在自相交");
                }
                String kcdjid = updateJsydJbxx(coordinateFile,ywid,ywid);
                log.info("更新业务信息成功,勘测定界ID：{}",kcdjid);
                if(StringUtils.isBlank(kcdjid)){
                    lspwFileLog.setErrorMsg("更新报批信息失败");
                    lspwFileLogMapper.insert(lspwFileLog);
                    return ServerResponse.createByErrorMessage("更新报批信息失败");
                }
                coordinateTransform(coordinateFile);
                String insertInfo = insertJsydDkxx(coordinateFile,kcdjid,ywid);
                log.info("插入地块信息,内容：{}",insertInfo);
                String areaInfo = areaCal(ywid);
                log.info("面积计算信息:{}",areaInfo);
            }
        } catch (Exception e) {
            e.printStackTrace();
            lspwFileLog.setErrorMsg(e.getMessage().substring(0,1999));
            lspwFileLogMapper.insert(lspwFileLog);
            return ServerResponse.createByErrorMessage(e.getMessage());
        }
        lspwFileLog.setStatus("1");
        lspwFileLogMapper.insert(lspwFileLog);
        return ServerResponse.createBySuccess(ywid);
    }
    @Autowired
    AnalyseService analyseService;

    public String areaCal(String ywid) throws Exception{
        AnalyseModel analyseModel = new AnalyseModel();
        analyseModel.setYwid(ywid);
        analyseModel.setFxlx(AnalyseType.MJJS.toString());
        analyseModel.setQsnd("201906");
        analyseModel.setGdnd("2016");
        analyseModel.setDlnd("2018");
        HandlerResult handlerResult = analyseService.analyse(analyseModel);
        return objectMapper.writeValueAsString(handlerResult);
    }
    /**
     * 插入地块信息
     * @param coordinateFile
     * @return
     */
    public String insertJsydDkxx(CoordinateFile coordinateFile,String kcdjId,String ywid) throws Exception{
        Map<String,Object> param = new HashMap<>();
        List<Map> dataMap = new ArrayList<>();
        for(Map<String,Object> map : coordinateFile.getLandCoordinates()){
            /**landDesc 地块描述信息*/
            Map<String,Object> descMap =(Map<String,Object>) map.get("landDesc");
            Map<String,Object> zbMap = (Map<String,Object>) map.get("transZbList");

            List<Map<String,Object>> jsydZbxxs = new ArrayList<>();
            ArrayList<Map<String,List<List<List>>>> ProcessList = (ArrayList<Map<String,List<List<List>>>>)zbMap.get("ProcessValue");
            List<List<List>> ringsList = ProcessList.get(0).get("rings");
            for(int x = 0 ; x < ringsList.size() ; x++){
                for(int  y = 0 ; y < ringsList.get(x).size() ; y++){
                    Map<String,Object> zbInfo = new HashMap<>();
                    zbInfo.put("xzb",ringsList.get(x).get(y).get(0));
                    zbInfo.put("yzb",ringsList.get(x).get(y).get(1));
                    zbInfo.put("dh",(y+1)+"");
                    zbInfo.put("xh",y+1);
                    zbInfo.put("qh",x+1);
                    jsydZbxxs.add(zbInfo);
                }
            }
            descMap.put("jsydZbxxs",jsydZbxxs);
            dataMap.add(descMap);
        }
        param.put("data",dataMap);
        param.put("acc_token","acc_token");
        param.put("kcdjid",kcdjId);
        param.put("ywid",ywid);
        log.info("插入地块参数：{}",objectMapper.writeValueAsString(param));
        HttpResult httpResult = httpAPIService.doPostByJsonParam(insertDkxxUrl,objectMapper.writeValueAsString(param));
        return httpResult.getBody();
    }


    /**
     * 自相交检查
     * @return
     */
    public String selfIntersectCheck(CoordinateFile coordinateFile) throws Exception{
        List<Map<String,Object>> landCoordinates = coordinateFile.getLandCoordinates();
        List<Map> paramList = new ArrayList<>();
        for(Map<String,Object> coordinateMap : landCoordinates){
            List<Map<String,Object>> arrayMap = (List<Map<String,Object>>)coordinateMap.get("GeometryArray");
            Map<String,Object> geometryMap = (Map<String,Object>)arrayMap.get(0).get("Geometry");
            Map<String,Object> targetMap = new HashMap<>();
            targetMap.put("rings",geometryMap.get("rings"));
            Map<String,String> wkMap = new HashMap<>();
            String dh = coordinateFile.getAttributeInfo().getDh();
            String wkid = "";
            if(dh.equals("37")){
                wkid = "4525";
            }else if(dh.equals("38")){
                wkid = "4526";
            }else {
                wkid = "4527";
            }
            wkMap.put("wkid",wkid);
            targetMap.put("spatialReference",wkMap);
            paramList.add(targetMap);
        }
        Map<String,Object> param = new HashMap<>();
        param.put("GeometryType","Polygon");
        param.put("GeometryArray",objectMapper.writeValueAsString(paramList));
        param.put("f","json");
        log.info("自相交"+objectMapper.writeValueAsString(param));
        HttpResult httpResult = httpAPIService.doPost(selfIntersectUrl,param);
        return httpResult.getBody();
    }

    /**
     * 多原坐标文件自相交检查
     * @param coordinateFiles
     * @return
     * @throws Exception
     */
    public HttpResult multipleOriginalSelfIntersectCheck(List<CoordinateFile> coordinateFiles) throws Exception {
        List<Map> paramList = new ArrayList<>();
        for(CoordinateFile coordinateFile : coordinateFiles) {
            List<Map<String,Object>> landCoordinates = coordinateFile.getLandCoordinates();
            for (Map<String, Object> coordinateMap : landCoordinates) {
                List<Map<String,Object>> arrayMap = (List<Map<String,Object>>)coordinateMap.get("GeometryArray");
                Map<String,Object> geometryMap = (Map<String,Object>)arrayMap.get(0).get("Geometry");
                Map<String,Object> targetMap = new HashMap<>();
                targetMap.put("rings",geometryMap.get("rings"));
                Map<String,String> wkMap = new HashMap<>();
                String dh = coordinateFile.getAttributeInfo().getDh();
                String wkid = "";
                if(dh.equals("37")){
                    wkid = "4525";
                }else if(dh.equals("38")){
                    wkid = "4526";
                }else {
                    wkid = "4527";
                }
                wkMap.put("wkid",wkid);
                targetMap.put("spatialReference",wkMap);
                paramList.add(targetMap);
            }
        }
        Map<String,Object> param = new HashMap<>();
        param.put("GeometryType","Polygon");
        param.put("GeometryArray",objectMapper.writeValueAsString(paramList));
        param.put("f","json");
        log.info("自相交"+objectMapper.writeValueAsString(param));
        HttpResult httpResult = httpAPIService.doPost(selfIntersectUrl,param);
        return httpResult;
    }

    /**
     * 多文件重叠分析
     * @return
     */
    public HttpResult multipleSelfIntersectCheck(List<CoordinateFile> coordinateFiles) throws Exception{
        return multipleGeoCheck(coordinateFiles,selfIntersectUrl);
    }


    public HttpResult multipleGeoCheck(List<CoordinateFile> coordinateFiles,String url) throws Exception{
        List<Map> paramList = new ArrayList<>();
        for(CoordinateFile coordinateFile : coordinateFiles){
            for(Map<String,Object> map : coordinateFile.getLandCoordinates()) {
                Map<String, Object> zbMap = (Map<String, Object>) map.get("transZbList");
                ArrayList<Map<String,List<List<List>>>> ProcessList =
                        (ArrayList<Map<String,List<List<List>>>>)zbMap.get("ProcessValue");
                List<List<List>> rings = ProcessList.get(0).get("rings");
                Map<String,Object> targetMap = new HashMap<>();
                targetMap.put("rings",rings);
                Map<String,String> wkMap = new HashMap<>();
                wkMap.put("wkid","4490");
                targetMap.put("spatialReference",wkMap);
                paramList.add(targetMap);
            }
        }
        Map<String,Object> param = new HashMap<>();
        param.put("GeometryType","Polygon");
        param.put("GeometryArray",objectMapper.writeValueAsString(paramList));
        param.put("f","json");
        log.info("重叠分析内容"+objectMapper.writeValueAsString(param));
        HttpResult httpResult = httpAPIService.doPost(url,param);
        return httpResult;
    }


    /**
     * 重叠检查
     * @param coordinateFile
     * @return
     */
    public String overlapCheck(CoordinateFile coordinateFile) throws Exception{
        List<Map<String,Object>> landCoordinates = coordinateFile.getLandCoordinates();
        List<Map> paramList = new ArrayList<>();
        for(Map<String,Object> coordinateMap : landCoordinates){
            List<Map<String,Object>> arrayMap = (List<Map<String,Object>>)coordinateMap.get("GeometryArray");
            Map<String,Object> geometryMap = (Map<String,Object>)arrayMap.get(0).get("Geometry");
            Map<String,Object> targetMap = new HashMap<>();
            targetMap.put("rings",geometryMap.get("rings"));
            Map<String,String> wkMap = new HashMap<>();
            String dh = coordinateFile.getAttributeInfo().getDh();
            String wkid = "";
            if(dh.equals("37")){
                wkid = "4525";
            }else if(dh.equals("38")){
                wkid = "4526";
            }else {
                wkid = "4527";
            }
            wkMap.put("wkid",wkid);
            targetMap.put("spatialReference",wkMap);
            paramList.add(targetMap);
        }
        Map<String,Object> param = new HashMap<>();
        param.put("GeometryType","Polygon");
        param.put("GeometryArray",objectMapper.writeValueAsString(paramList));
        param.put("f","json");
        log.info("重叠分析内容"+objectMapper.writeValueAsString(param));
        HttpResult httpResult = httpAPIService.doPost(overlapUrl,param);
        return httpResult.getBody();
    }


    /**
     * 多文件重叠分析
     * @return
     */
    public HttpResult multipleOverlapCheck(List<CoordinateFile> coordinateFiles) throws Exception{
        return multipleGeoCheck(coordinateFiles,overlapUrl);
    }

    /**
     * 获取rings
     * @param coordinateFile
     * @return
     */
    public double[][][] getRings(CoordinateFile coordinateFile){
        List<double[]> totalCoordinateList = new ArrayList<>();
        List<Map<String,Object>> coordinateList = coordinateFile.getLandCoordinates();
        try {
            log.info("内容:{}",objectMapper.writeValueAsString(coordinateList));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        for(int i = 0 ; i < coordinateList.size() ; i++){
            Map<String,Object> coordinateMap = coordinateList.get(i);
            List<Map<String,Object>> geoArray = (List<Map<String,Object>>)coordinateMap.get("GeometryArray");
            Map<String,Object> geometry =(Map<String,Object>) geoArray.get(0).get("Geometry");
            double[][][] rings_t = (double[][][])geometry.get("rings");
            for(int ringIndex = 0 ; ringIndex < rings_t.length ; ringIndex++){

            }

            double[][] rings_s = rings_t[0];
            for(int  y = 0 ; y < rings_s.length ; y++){
                if(y < rings_s.length - 1){
                    totalCoordinateList.add(rings_s[y]);
                }
            }
        }

        double[][][] rings = new double[1][totalCoordinateList.size()+1][2];
        for(int k = 0 ; k < totalCoordinateList.size() ; k++){
            rings[0][k] = totalCoordinateList.get(k);
        }
        rings[0][totalCoordinateList.size()] = totalCoordinateList.get(0);
        return rings;
    }

    /**
     * 更新经办信息
     * @param coordinateFile
     * @param ywid
     * @param newId
     * @return
     * @throws Exception
     */
    private String updateJsydJbxx(CoordinateFile coordinateFile,String ywid,String newId) throws Exception{
        Map<String,Object> data = coordinateFile.getAllAttribute();
        data.put("xmmc",coordinateFile.getProjectInfo().getXmmc());

        Map<String,Object> param = new HashMap<>();
        param.put("acc_token","acc_token");
        param.put("data",data);
        param.put("newId",newId);
        param.put("yhid",yhid);
        param.put("ywid",ywid);
        log.info("参数：{}",objectMapper.writeValueAsString(param));
        HttpResult httpResult = httpAPIService.doPostByJsonParam(updateJbxxUrl,objectMapper.writeValueAsString(param));
        String kcdjId = "";
        if(httpResult.getCode()==200){
            Map<String,String> map = objectMapper.readValue(httpResult.getBody(),Map.class);
            if(map.get("ret_code").equals("1")){
                kcdjId = map.get("kcdjid");
            }else{
                throw new Exception("更新业务信息失败!!");
            }
        }
        return kcdjId;
    }

    /**
     * 上传文件
     * @return
     */
    public String uploadTxtFile(String fileContent,String ywid,String fileName) throws Exception{
        Map<String,Object> param = new HashMap<>();
        param.put("clientip","127.0.0.1");
        param.put("filecontent",fileContent);
        param.put("yhid",yhid);
        param.put("ywid",ywid);
        param.put("filename",fileName);
        param.put("zblx","");
        HttpResult result = httpAPIService.doPost(txtUploadUrl,param);
        return result.getBody();
    }

    /**
     * 上传文件
     * @return
     */
    public String uploadTxtFile(List<String> fileContentList, String ywid, List<String> fileNameList, String zblx) throws Exception{
        List<Map<String, String>> fileDatas = new ArrayList<>();
        if(fileContentList.size() == fileNameList.size()) {
            for (int i = 0; i < fileNameList.size(); i++) {
                Map<String, String> map = new HashMap<>();
                map.put("fileName", fileNameList.get(i));
                map.put("fileContent", fileContentList.get(i));
                fileDatas.add(map);
            }
        }
        Map<String,Object> param = new HashMap<>();
        param.put("clientip","127.0.0.1");
        param.put("fileDatas", fileDatas);
        param.put("yhid",yhid);
        param.put("ywid",ywid);
        param.put("zblx",zblx);
        HttpResult result = httpAPIService.doPostByJsonParam(batchTxtUpload, objectMapper.writeValueAsString(param));
        return result.getBody();
    }

    /**
     * 坐标转换
     * @param coordinateFile
     * @return
     */
    public void coordinateTransform(CoordinateFile coordinateFile) throws Exception{

        String corTransName = "";
        String dh = coordinateFile.getAttributeInfo().getDh();
        if(dh.equals("37")){
            corTransName = "方案_4490_37";
        }else if(dh.equals("38")){
            corTransName = "方案_4490_38";
        }else if(dh.equals("39")){
            corTransName = "方案_4490_39";
        }
        for(Map<String,Object> map : coordinateFile.getLandCoordinates()){
            Map<String,Object> coordinateTransObj = new HashMap<>(5);
            coordinateTransObj.put("Type","geometry");
            try {
                coordinateTransObj.put("FileValue",objectMapper.writeValueAsString(map));
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            coordinateTransObj.put("GeometryType","polygon");
            coordinateTransObj.put("CoordTransformName",corTransName);
            coordinateTransObj.put("f","json");
            HttpResult result = httpAPIService.doPost(coordinateTransUrl,coordinateTransObj);
            if(result.getCode()==200){
                Map<String,Object> resultMap = objectMapper.readValue(result.getBody(),Map.class);
                map.put("transZbList",resultMap);
            }
        }
    }


    /**
     * 构建建设用地经办信息
     * @return
     * @param userId
     */
    public String createJsydJbxx(String userId) throws Exception{
        /**
         * {"acc_token":"acc_token","lcdm":"XJSH","ywdl":"TDGL","ywxl":"JSYDSP","ywlx":"PCBP","pclx":"CSFPC","yhid":"2313"}
         */
        String ywid = "";
        Map<String,Object> params = new HashMap<>(7);
        params.put("acc_token","acc_token");
        params.put("lcdm",lcdm);
        params.put("ywdl",ywdl);
        params.put("ywxl",ywxl);
        params.put("ywlx",ywlx);
        params.put("pclx",pclx);
        if(userId!=null){
            params.put("yhid",userId);
        }else{
            params.put("yhid",yhid);
        }
        log.info("------------------jbxxCreateUrl:"+jbxxCreateUrl+"------------------------");
        log.info("------------------params:"+JSONObject.toJSONString(params)+"------------------------");
        HttpResult httpResult = httpAPIService.doPost(jbxxCreateUrl,params);
        if(httpResult.getCode()==200){
            Map<String,String> resultMapper = objectMapper.readValue(httpResult.getBody(),Map.class);
            if(resultMapper.get("ret_code").equals("1")){
                ywid = resultMapper.get("ywid");
            }else {
                throw new Exception(httpResult.getBody());
            }
        }
        return ywid;
    }


    /**
     * 获取远程文件
     * @param filePath
     * @return
     * @throws Exception
     */
    public String getFileContent(String filePath) throws Exception{
        /**默认读取mongodb远程文件*/
        log.info("读取文件,文件地址:{}",filePath);
        String fileContent = httpAPIService.doGet(filePath);
        log.info("读取成功");
        return fileContent;
    }

    /**
     * 坐标检查
     * @param fileContent
     * @return
     */
    public boolean coordinateCheck(String fileContent) throws Exception{
        boolean isOk = false;
        Map<String,Object> paramObj = new HashMap<>();
        paramObj.put("fileContent",fileContent);

        HttpResult httpResult = httpAPIService.doPost(coordinateCheckUrl,paramObj);
        log.info("坐标检查结束，内容:{}",httpResult.getBody());
        if(httpResult.getCode() == 200){
            Map<String,String> resultMapper = objectMapper.readValue(httpResult.getBody(),Map.class);
            if(resultMapper.get("result").equals("未发现错误！")){
                isOk = true;
            }
        }
        return isOk;
    }

    /**
     *
     * @param proInfos
     * @return
     * @throws Exception
     */

    public String batchExport(String proInfos) throws Exception{
        List<String> filePaths = new ArrayList<>();
        String[] proInfoCollection = proInfos.split(",");
        for(String proInfo:proInfoCollection){
            if(!StringUtils.isBlank(proInfo)){
                String[] proDetail = proInfo.split("-");
                String tmpPath = singleExport(proDetail[0],proDetail[1]);
                filePaths.add(tmpPath+","+proDetail[1]);
            }
        }

        /**压缩文件*/
        int readLen=0;
        byte[] buf=new byte[10240];
        String zipPath = tmpFilePath + File.separator + UUID.randomUUID().toString().replaceAll("-","")+".zip";
        ZipOutputStream targetZos = new ZipOutputStream(new FileOutputStream(zipPath), Charset.forName("GBK"));
        for(String fileInfo : filePaths){
            String filePath = fileInfo.split(",")[0];
            File f = new File(filePath);
            ZipEntry entry = new ZipEntry(f.getName());
            targetZos.putNextEntry(entry);
            InputStream is=new BufferedInputStream(new FileInputStream(f));
            while ((readLen=is.read(buf, 0, 10240))!=-1) {
                targetZos.write(buf, 0, readLen);
            }
            is.close();
        }
        targetZos.close();

        log.info("压缩完毕,压缩地址{}",zipPath);
        return zipPath;
    }

    public String singleExport(String ywid,String xmmc) throws Exception{
        Map<String,Object> param = new HashMap<>();
        param.put("CSZBYJJBNTFX","true");
        param.put("GHDLFX","true");
        param.put("JSYDGZQFX","true");
        param.put("QSFX","true");
        param.put("TZHDLFX","true");
        param.put("ZPHXFX","true");
        param.put("appId","1");
        param.put("dlfx_bpmj","show");
        param.put("dlfx_hydl","show");
        param.put("export","export_ywj_fxjg");
        param.put("ywid",ywid);
        param.put("ywxl","LSPW");
        Map<String,Object> mapParm = new HashMap<>();
        mapParm.put("mapParm",param);
        /**查询文件**/
        HttpResult httpResult = httpAPIService.doPostByJsonParam(queryExport,objectMapper.writeValueAsString(mapParm));
        if(httpResult.getCode()==200){
            Map<String,String> fileMap = objectMapper.readValue(httpResult.getBody(),Map.class);
            String remoteFileName = fileMap.get("result");
            /**构建文件下载地址**/
            String filePath = tmpFilePath + File.separator + xmmc+"_" + UUID.randomUUID().toString().replaceAll("-","") + ".xls";
            String donwUrl = downExport + "?sfilename="+remoteFileName+"&dfilename="+remoteFileName;
            String xlsPath = httpAPIService.downloadFile(donwUrl,filePath);
            return xlsPath;
        }
        return null;
    }

    /**
     * 基础班坐标批量转换政务版坐标
     * @param files
     * @return
     */
    public ServerResponse batchTransCoord(MultipartFile[] files) {
        ServerResponse serverResponse = ServerResponse.createByErrorMessage("转换坐标文件出现异常");
        List<String> filePathList = new ArrayList<String>();
        /**压缩文件*/
        int readLen=0;
        byte[] buf=new byte[10240];
        String zipPath = tmpFilePath + File.separator + UUID.randomUUID().toString().replaceAll("-","")+".zip";
        ZipOutputStream targetZos = null;
        try {
            targetZos = new ZipOutputStream(new FileOutputStream(zipPath), Charset.forName("GBK"));
            for (int i = 0; i < files.length; i++) {
                MultipartFile file = files[i];
                String fileName = file.getOriginalFilename();
                try {
                    /**获取文件编码**/
                    CpdetectorEncoding cpdetectorEncoding = new CpdetectorEncoding();

                    /**获取文件编码*/
                    Charset charsetName = cpdetectorEncoding.getFastEncoding(file.getBytes());
                    if(charsetName.name().equals("x-EUC-TW")){
                        charsetName = Charset.forName("GBK");
                    }
                    log.info("charsetName:{}", charsetName);
                    String content = new String(file.getBytes(),charsetName);

                    String centerMedianStr = content.split("带号=")[1].split("\\n|\\r")[0];
                    int centerMedian = 3 * Integer.parseInt(centerMedianStr);
                    Map<String,Object> param = new HashMap<>();
                    param.put("filename", fileName);
                    param.put("centerMedian", centerMedian);
                    param.put("filevalue", content);
                    HttpResult httpResult = httpAPIService.doPostByJsonParam(batchTransCoordUrl, objectMapper.writeValueAsString(param));
                    // log.info("内容：{}",httpResult.getBody());
                    JSONObject jsonObject = JSONObject.parseObject(httpResult.getBody());
                    JSONObject data = jsonObject.getJSONObject("data");
                    if(data == null || "success".equalsIgnoreCase(data.getString("code"))) {
                        String newFileName = data.getString("filename");
                        String newContent = data.getString("content");
                        String filePath = tmpFilePath + File.separator + newFileName;
                        // 创建新的文件
                        FileUtil.createFile(filePath, newContent);
                        File f = new File(filePath);
                        InputStream is = new BufferedInputStream(new FileInputStream(f));
                        ZipEntry entry = new ZipEntry(f.getName());
                        targetZos.putNextEntry(entry);
                        while ((readLen=is.read(buf, 0, 10240))!=-1) {
                            targetZos.write(buf, 0, readLen);
                        }
                        is.close();
                        // 删除新的文件
                        FileUtil.delFile(filePath);
                    } else {
                        serverResponse = ServerResponse.createByErrorMessage("转换坐标文件：【"+ fileName +"】出现异常，坐标格式不符合《粤国土资利用发〔2018〕25号（附件2）》文件要求，请调整坐标格式后再导入");
                    }
                } catch (Exception e) {
                    serverResponse = ServerResponse.createByErrorMessage("转换坐标文件：【"+ fileName +"】出现异常，坐标格式不符合《粤国土资利用发〔2018〕25号（附件2）》文件要求，请调整坐标格式后再导入");
                    e.printStackTrace();
                    return serverResponse;
                }
            }
            log.info("压缩完毕，压缩地址{}", zipPath);
//            Map<String, Object> resultMap = new HashMap<String, Object>();
//            resultMap.put("fileName", zipPath);
//            String zipContent = FileUtil.getString(zipPath);
//            resultMap.put("content", zipContent);
//            log.info("压缩包内容{}", zipContent);
            // 删除压缩包
//            FileUtil.delFile(zipPath);
            serverResponse = ServerResponse.createBySuccess("转换坐标文件成功", zipPath);
        } catch (Exception e) {
            serverResponse = ServerResponse.createByErrorMessage("压缩坐标文件出现异常");
            e.printStackTrace();
        } finally {
            try {
                if (targetZos != null) {
                    targetZos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return serverResponse;
    }
}
